package com.junction.util;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import org.bytedeco.libfreenect2.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.junction.cache.CacheUtil;
import com.junction.controller.CameraController;
import com.junction.pojo.Config;
import org.springframework.util.StringUtils;

/**
 * @Title TimerUtil.java
 * @description 定时任务
 * @author houzw
 **/
@Component
public class FileCleanThread implements CommandLineRunner {
	private static org.slf4j.Logger logger = LoggerFactory.getLogger(FileCleanThread.class);


	@Autowired
	private Config config;// 配置文件bean

	public static Timer timer;

	@Override
	public void run(String... args) throws Exception {
		// 超过5分钟，结束推流
		timer = new Timer("timeTimer");
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				LocalDateTime now = LocalDateTime.now();
				// 往前推60天
				LocalDateTime sixtyDaysAgo = now.minus(60, ChronoUnit.DAYS);
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
				String formattedDate = sixtyDaysAgo.format(formatter);
				long sixtyDaysAgomillis = sixtyDaysAgo.toInstant(ZoneOffset.UTC).toEpochMilli();

				logger.info("开始执行定时文件清理任务...");
				// 获取目录下的视频和日志，删除一个月之前的
				File directory = new File("./videos");
				File[] files = directory.listFiles();

				if (files != null) {
					for (File file : files) {
						if (file.isFile()) {
							if(file != null && !StringUtils.isEmpty(file.getName())){
								try {
									Path path = Paths.get(file.getPath());
									BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
									if(sixtyDaysAgomillis > attrs.creationTime().toMillis()){
										String filename = file.getName();
										if(!StringUtils.isEmpty(filename)  && filename.contains("output")  && filename.contains(".mp4")){
											filename = filename.substring(filename.indexOf("_") + 1,filename.indexOf(".mp4"));
											long existFileTime = Long.parseLong(filename);
											long sixtyDaysTime  = Long.parseLong(formattedDate);
											if(sixtyDaysTime > existFileTime){
												file.deleteOnExit();
											}
										}
									}
								} catch (IOException e) {
									throw new RuntimeException(e);
								}
							}
						}
					}
				} else {
					logger.info("目录不存在或无法访问.");
				}
				logger.info("定时文件清理任务执行完毕...");
			}
		}, 1, 1000 * 60);
	}
}
